<template>
  <div class="form-container">
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="name">申报人姓名</label>
        <input type="text" id="name" v-model="formData.declarerName" placeholder="请输入您的姓名" />
      </div>
      <div class="form-group">
        <label for="gender">性别</label>
        <el-select id="gender" v-model="formData.gender" placeholder="请选择性别">
          <el-option label="男" value="M" />
          <el-option label="女" value="F" />
        </el-select>
      </div>
      <div class="form-group">
        <label for="phone">联系方式</label>
        <input type="text" id="phone" v-model="formData.phone" placeholder="请输入电话号码" />
      </div>

      <div class="form-group">
        <label for="phone">家庭人均收入</label>
        <input type="text" id="decimal" v-model="formData.familyIncome" placeholder="请输入家庭人均收入(单位：元)" />
      </div>
      <div class="form-group">
        <label for="address">联系地址</label>
        <el-cascader id="address" v-model="formData.address" :options="addressOptions" placeholder="请选择省市县" clearable
          :props="{ checkStrictly: true, expandTrigger: 'hover' }" />
      </div>
      <div class="form-group">
        <label for="detailAddress">详细地址</label>
        <input type="text" id="detailAddress" v-model="formData.detailAddress" placeholder="请输入详细地址" />
      </div>
      <div class="form-group">
        <label for="idCard">身份证号</label>
        <input type="text" id="idCard" v-model="formData.idCard" placeholder="请输入身份证号" />
      </div>

      <!-- 风险类型 -->
      <div class="form-group">
        <label>风险类型</label>
        <div class="risk-options-grid">
          <div class="risk-option" v-for="option in riskOptions" :key="option.value">
            <input type="checkbox" :id="option.id" v-model="formData.riskType" :value="option.value"
              @change="handleRiskTypeChange">
            <label :for="option.id">{{ option.label }}</label>
          </div>
          <div class="risk-option" v-if="formData.riskType.includes('其他')">
            <el-input v-model="formData.otherRisk" placeholder="请注明其他风险类型" clearable />
          </div>
        </div>
      </div>

      <div class="form-group">
        <label for="riskLevel">风险级别</label>
        <el-select id="riskLevel" v-model="formData.riskLevel" placeholder="请选择风险级别">
          <el-option label="一级" value="一级" />
          <el-option label="二级" value="二级" />
          <el-option label="三级" value="三级" />
        </el-select>
      </div>

      <div class="member-buttons">
        <el-button type="primary" icon="el-icon-plus" @click="addFamilyMember" class="b">
          + 添加家庭成员
        </el-button>
        <el-button type="info" icon="el-icon-view" @click="showFamilyMembers">
          查看家庭成员
        </el-button>
      </div>

      <!-- 家庭成员信息 -->
      <el-dialog v-model="dialogVisible" title="家庭成员信息" width="50%" center>
        <div v-if="familyMemberData.length === 0" class="empty-message">
          暂无家庭成员信息
        </div>
        <div v-else class="member-list">
          <div v-for="(member, index) in familyMemberData" :key="index" class="member-item">
            <h3 class="member-name">{{ member.name }}</h3>
            <div class="member-info">
              <p><span>性别：</span>{{ member.gender }}</p>
              <p><span>身份证号：</span>{{ member.idCard }}</p>
              <p><span>与户主关系：</span>{{ member.relation }}</p>
              <p><span>民族：</span>{{ member.nation || '未填写' }}</p>
              <p><span>政治面貌：</span>{{ member.politicalStatus || '未填写' }}</p>
              <p><span>文化程度：</span>{{ member.education || '未填写' }}</p>
              <p><span>健康状况：</span>{{ member.health || '未填写' }}</p>
              <p v-if="member.laborskills"><span>掌握技能：</span>{{ member.laborskills }}</p>
            </div>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <div class="button-group">
        <el-button type="success" size="large" @click="handleSubmit">
          <i class="el-icon-check"></i> 提交
        </el-button>
        <el-button type="info" size="large" @click="resetForm">
          <i class="el-icon-refresh"></i> 重置
        </el-button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { addApplication, selectByCard } from "@/api/application"

const router = useRouter();

const riskOptions = ref([
  { id: 'illness', value: '因病', label: '因病' },
  { id: 'study', value: '因学', label: '因学' },
  { id: 'disability', value: '因残', label: '因残' },
  { id: 'naturalDisaster', value: '因自然灾害', label: '因自然灾害' },
  { id: 'accident', value: '因意外事故', label: '因意外事故' },
  { id: 'projectFailure', value: '因产业项目失败', label: '因产业项目失败' },
  { id: 'employmentInstability', value: '因务工就业不稳', label: '因务工就业不稳' },
  { id: 'lackLabor', value: '缺劳动力', label: '缺劳动力' },
  { id: 'other', value: '其他', label: '其他' }
]);

// 家庭成员数据
const familyMemberData = ref([]);
const dialogVisible = ref(false);

// 家庭成员列表
const familyMembers = ref([
  { name: '', relationship: '' }
]);



// 查看家庭成员信息
const showFamilyMembers = () => {
  // 从localStorage获取家庭成员数据
  const savedData = localStorage.getItem('familyMemberData');
  if (savedData) {
    try {
      familyMemberData.value = [JSON.parse(savedData)]; // 假设只保存了一个家庭成员
      dialogVisible.value = true;
    } catch (error) {
      console.error('Failed to parse family member data:', error);
      ElMessage.error('获取家庭成员信息失败');
    }
  } else {
    ElMessageBox.info('暂无家庭成员信息，请先添加家庭成员');
  }
};

// 处理风险类型变更
const handleRiskTypeChange = () => {
  if (!formData.value.riskType.includes('其他')) {
    formData.value.otherRisk = '';
  }
};

// 模拟省市县数据
const addressOptions = ref([
  {
    value: '110000',
    label: '北京市',
    children: [
      {
        value: '110100',
        label: '北京市',
        children: [
          { value: '110101', label: '东城区' },
          { value: '110102', label: '西城区' },
          { value: '110105', label: '朝阳区' },
        ],
      },
    ],
  },
  {
    value: '310000',
    label: '上海市',
    children: [
      {
        value: '310100',
        label: '上海市',
        children: [
          { value: '310101', label: '黄浦区' },
          { value: '310104', label: '徐汇区' },
          { value: '310105', label: '长宁区' },
        ],
      },
    ],
  },
]);

const formData = ref({
  declarerName: '',
  gender: '',
  phone: '',
  familyIncome: '',
  address: [],
  detailAddress: '',
  idCard: '',
  riskType: [],
  otherRisk: '',
  riskLevel: '',
});

// 页面加载时从localStorage读取数据
onMounted(() => {
  const savedData = localStorage.getItem("application");
  if (savedData) {
    try {
      formData.value = JSON.parse(savedData);
    } catch (error) {
      console.error('Failed to parse saved form data:', error);
    }
  }
});

const handleSubmit = () => {
  const submitData = {
    declarerName: formData.value.declarerName,
    gender: formData.value.gender,
    phone: formData.value.phone,
    familyIncome: formData.value.familyIncome,
    // 处理地址数据（数组转字符串）
    address: formData.value.address.join('/'),
    detailAddress: formData.value.detailAddress,
    idCard: formData.value.idCard,
    // 处理风险类型数据（数组转逗号分隔字符串）
    riskType: formData.value.riskType.join(','),
    otherRisk: formData.value.otherRisk,
    riskLevel: formData.value.riskLevel,
    // 其他需要提交的字段...
  };

  // 2. 打印调试
  console.log('提交的表单数据:', formData.value, '家庭成员:');
  formData.riskType = formData.value.riskType.join(','), // 用逗号连接风险类型
    formData.address = formData.value.address.join('/')
  addApplication(submitData).then(res => {
    if (res.code == 2000) {
      ElMessage.success('添加成功')
    }
  })
  localStorage.setItem("application", JSON.stringify(formData.value));
  ElMessage.success('表单提交成功！');
};

// 添加家庭成员
const searchParams = reactive({
  card: formData.idCard,
})
const addFamilyMember = () => {
  // const declarationId = selectByCard(formData.idCard)
  router.push('/addfamily');
  ElMessage.success('即将跳转到添加家庭成员页面');
};

const resetForm = () => {
  formData.value = {
    name: '',
    gender: '',
    phone: '',
    decimal: '',
    address: [],
    detailAddress: '',
    idCard: '',
    riskType: [],
    otherRisk: '',
    riskLevel: '',
  };
  familyMembers.value = [{ name: '', relationship: '' }];
  localStorage.removeItem("application");
  ElMessage.info('表单已重置！');
};
</script>

<style scoped>
.b {
  text-align: center;
}

.form-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 80px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 25px;
}

.button-group button {
  padding: 10px 20px;
  font-size: 16px;
}

.family-members {
  margin: 30px 0;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}

.family-member {
  display: grid;
  grid-template-columns: 1fr 1fr auto;
  gap: 15px;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e4e7ed;
}

.family-member:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.family-member .el-button {
  margin-top: 30px;
  align-items: center;
  justify-content: center;
}

.risk-options-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px 20px;
  margin-top: 10px;
}

.risk-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.risk-option input[type="checkbox"] {
  width: 18px;
  height: 18px;
}

/* 新增的按钮组样式 */
.member-buttons {
  display: flex;
  gap: 10px;
  margin: 20px 0;
  justify-content: start;
}

/* 模态框样式 */
.empty-message {
  text-align: center;
  padding: 20px;
  color: #6b7280;
}

.member-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.member-item {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}

.member-name {
  font-weight: bold;
  margin-bottom: 10px;
  color: #2563eb;
}

.member-info {
  font-size: 14px;
  line-height: 1.5;
}

.member-info p {
  margin: 5px 0;
}

.member-info span {
  font-weight: 500;
  color: #4b5563;
}

/* 响应式布局 */
@media (max-width: 576px) {
  .risk-options-grid {
    grid-template-columns: 1fr;
  }

  .member-buttons {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>